import logging

from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView

from unicom.captcha import Captcha
from io import BytesIO
from PIL import Image
logger = logging.getLogger("django")

@method_decorator(csrf_exempt, name='dispatch')
class View(APIView):
    def crack_captcha(request):
        """
        校验、保存用户参数，保存用户信息
        :param reqeust:
        :return:
        """
        try:
            import pickle
            image = Image.open(BytesIO(request.body))
            # if type(data)!=PngImageFile:
            #     return Response({"retcode":"","retinfo":"image type error"})
            breaker = Captcha()
            code = breaker.crack_captcha(image)
            print(code)
        except Exception as e:
            logger.exception("异常{}".format(repr(e)))
            code=''
        import json
        return HttpResponse(json.dumps({"retcode":code,"retinfo":"success"}))